package com.css.zfzx.sjcj.modules.statistics.dao.primary.impl;

import com.css.zfzx.sjcj.modules.statistics.dao.primary.SuperDao;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.Iterator;

/**
 * @Description: pc-statistics
 * @Author: lhl
 * @CreateDate: 2021/10/9 9:16
 */
@Repository
public class SuperDaoImpl<T> implements SuperDao<T> {
    @PersistenceContext
    private EntityManager em;
    private static final Logger log = LoggerFactory.getLogger(SuperDaoImpl.class);
    @Value("${spring.jpa.properties.hibernate.jdbc.batch_size:1000}")
    private int BATCH_SIZE;

    @Override
    @Transactional
    public <S extends T> Iterable<S> batchUpdate(Iterable<S> var1) {
        Iterator<S> iterator = var1.iterator();
        int index = 0;
        while (iterator.hasNext()) {
            em.merge(iterator.next());
            index++;
            if (index % BATCH_SIZE == 0) {
                System.out.println(index);
                em.flush();
                em.clear();
            }
            //if(index % 10000 == 0) System.out.println("更新了："+index +" 条数据");
        }
        System.out.println(index);
        if (index % BATCH_SIZE != 0) {
            em.flush();
            em.clear();
        }
        return var1;
    }

    @Override
    @Transactional
    public <S extends T> Iterable<S> batchSave(Iterable<S> var1) {
        Iterator<S> iterator = var1.iterator();
        int index = 0;
        while (iterator.hasNext()) {
            em.persist(iterator.next());
            index++;
            if (index % BATCH_SIZE == 0) {
                em.flush();
                em.clear();
            }
        }
        if (index % BATCH_SIZE != 0) {
            em.flush();
            em.clear();
        }
        return var1;
    }
}
